<template>
	<view class="map-wrap">
		<map
		  id="map"
		  :longitude="longitude"
		  :latitude="latitude"
		  :markers="markers"
		  :polyline="polyline"
		  :include-points="includePoints"
		  style="width: 100%; height: 300px;"
		  :scale="scale"
		></map>
	</view>
</template>

<script>
	export default {
		data() {
			
			return {
				markers: [],
				polyline: [],
				includePoints:[],
				scale:16,
				longitude:"115.44702",
				latitude:"38.865815",
			};
		},
		props: {
			pathList: {
			  type: Object,
			  default() {
				return {};
			  },
			},
		},
		watch: {
			pathList: {
			  handler(val) {
				if (val) {
				  this.initMap();
				  // console.log(val);
				}
			  },
			  deep: true,
			  immediate: true,
			}
		},
		onLoad(option) {
		},
		mounted() {  
		},
		created() {
			
		},
		methods: {
			initMap() {
				this.getDriverLine()
			},
			getDriverLine() {
			  const that = this
			  const key = '26b2ecf002ebe30ce54bfa3100e0dfc6'
			  const origin = that.pathList.origin
			  const destination = that.pathList.destination
			  const waypoints = that.pathList.waypoints
			  that.markers = []
			  //给起点坐标一个图标
			  that.startingPoint()
			  //给终点坐标一个图标
			  that.endPoint()
			  if (that.pathList.waypoints) {
				// 给途经点图标
				that.wayPoint()
			  }
			  
			  uni.request({
			    url: `https://restapi.amap.com/v3/direction/driving?origin=${origin}&destination=${destination}&waypoints=${waypoints}&key=${key}`,
			    success: (res) => {
					// console.log('返回的路径', res.data.route);
			      const data = res.data.route
			      var points = []
			      if (data.paths && data.paths[0] && data.paths[0].steps) {
			        var steps = data.paths[0].steps;
			        for (var i = 0; i < steps.length; i++) {
			          //将每一步的数据放到points数组中
			          var poLen = steps[i].polyline.split(";")
			          for (var j = 0; j < poLen.length; j++) {
			            points.push({
			              longitude: parseFloat(poLen[j].split(",")[0]),
			              latitude: parseFloat(poLen[j].split(",")[1]),
			            })
			          }
			        }
			      }
			      that.polyline = [{
			        points: points,
			        color: "#0091ff",
					width: 10,//线的宽度
					borderWidth: 2, //线的厚度
					arrowLine: true, //带箭头的线
			      }]
				  that.includePoints = points
				  
				  let centralPoint =  that.pathList.origin.split(',').map(item => Number(item))
				  let obj = {
					centralPoint: centralPoint,
					otherPoint: points
				  }
				  this.longitude = Number(centralPoint[0])
				  this.latitude = Number(centralPoint[1])
				  // console.log('中心点',centralPoint,this.longitude,this.latitude);
				  that.furthest(obj)
			    }
			  })
			},
			// 规划路线的时候给起点一个marker，
			startingPoint() {
				let origin = this.pathList.origin.split(',').map(item => Number(item))
				let point = [
				  {
					id: 1,
					width: 40,
					height: 40,
					title: this.pathList.originName,//标注点名
					longitude: origin[0],
					latitude: origin[1],
					iconPath: "/static/images/map/start.png",
					anchor: {
					  x: 0.5,
					  y: 1,
					},
				  },
				];
				this.markers = this.markers.concat(point);
			},
			// 规划路线的时候给终点一个marker，
			endPoint() {
				let destination = this.pathList.destination.split(',').map(item => Number(item))
				let point = [
				  {
					id: 2,
					width: 40,
					height: 40,
					title: this.pathList.destinationName,//标注点名
					longitude: destination[0],
					latitude: destination[1],
					iconPath: "/static/images/map/end.png",
					anchor: {
					  x: 0.5,
					  y: 1,
					},
				  },
				];
				this.markers = this.markers.concat(point);
			},
			//规划路线的时候给途经点一个marker，
			wayPoint(){
				let waypoints = this.pathList.waypoints.split(';')
				let waypointsName = this.pathList.waypointsName.split(';')
				waypoints = waypoints.filter(item => !!item)
				waypoints.map((item, index) => {
				  let arr = item.split(',').map(i => Number(i))		
				  let point = [
				    {
				  	id: 2,
				  	width: 40,
				  	height: 40,
				  	title: `目的地${index + 1}${waypointsName[index]}`,//标注点名
				  	longitude: arr[0],
				  	latitude: arr[1],
				  	iconPath: "/static/images/map/mid.png",
				  	anchor: {
				  	  x: 0.5,
				  	  y: 1,
				  	},
				    },
				  ];
				  this.markers = this.markers.concat(point);
				})
				
				
			},
			
			// 根据坐标点计算出scale
			furthest(obj) {
				// console.log(obj)
				var EARTH_RADIUS = 6378137.0; //单位M
				var PI = Math.PI;
				// 转为角度
				function getRad(d){
				return d*PI/180.0;
				}
				
				let distance = {
					// 将地球按照圆形计算
					getGreatCircle: function (coordinate1,coordinate2) {
						var lat1 = coordinate1[0] // 纬度
						var lat2 = coordinate2[0]
						var lng1 = coordinate1[1] // 经度
						var lng2 = coordinate2[1]
						
						var radLat1 = getRad(lat1);
						var radLat2 = getRad(lat2);
							
						var a = radLat1 - radLat2;
						var b = getRad(lng1) - getRad(lng2);
							
						var s = 2*Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) + Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
						s = s*EARTH_RADIUS;
						s = Math.round(s*10000)/10000.0;
						return s;
					},
					// 将地球按照椭圆进行计算
					getFlattern: function (coordinate1, coordinate2){
						var lat1 = coordinate1[0] // 纬度
						var lat2 = coordinate2[0]
						var lng1 = coordinate1[1] // 经度
						var lng2 = coordinate2[1]
						
						var f = getRad((lat1 + lat2)/2);
						var g = getRad((lat1 - lat2)/2);
						var l = getRad((lng1 - lng2)/2);
				
						var sg = Math.sin(g);
						var sl = Math.sin(l);
						var sf = Math.sin(f);
				
						var s,c,w,r,d,h1,h2;
						var a = EARTH_RADIUS;
						var fl = 1/298.257;
				
						sg = sg*sg;
						sl = sl*sl;
						sf = sf*sf;
				
						s = sg*(1-sl) + (1-sf)*sl;
						c = (1-sg)*(1-sl) + sf*sl;
				
						w = Math.atan(Math.sqrt(s/c));
						r = Math.sqrt(s*c)/w;
						d = 2*w*a;
						h1 = (3*r -1)/2/c;
						h2 = (3*r +1)/2/s;
				
						return d*(1 + fl*(h1*sf*(1-sg) - h2*(1-sf)*sg));
					}
				
				}
			
				// obj包含中心点坐标和其他所有的坐标位置
				// 处理obj传入的参数
				let centralPoint = obj.centralPoint // 中心点
				let otherPoint = obj.otherPoint     // 二维数组存放其他坐标点
				
				// 循环遍历得出距离最远的1个坐标然后*2
				let farthestCoordinate = [] // 当前最远坐标
				let farthestDistance = 0    // 最远距离
				let dis = null              // 存储当前距离
				for(let i in otherPoint) {
					let newLocation = []
					newLocation[0] = otherPoint[i].longitude
					newLocation[1] = otherPoint[i].latitude
			
					dis = distance.getGreatCircle(centralPoint, newLocation)
					if(dis > farthestDistance) {
						farthestDistance = dis
						farthestCoordinate = newLocation
					}
				}
				
				farthestDistance = farthestDistance/1000 // 转为km
			
				// 根据坐标计算出合理的比例尺寸
				let surface = [500, 200, 100, 50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05, 0.02]
			
				for(let i in surface) {
					if(farthestDistance > surface[i]) {
						let scale = 5 + Number(i)
						this.scale =  scale
						console.log(this.scale);
						return
					}
				}
				
				// this.scale =  16
			},
			
		},
	};
</script>

<style lang="scss" scoped>
	.map-wrap{
		.map{
			width: 100%;
			height: 200px;
		}
	}
</style>